package com.sharker.myproject.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sharker.myproject.domain.User;

@Controller
public class SystemController {

	
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String login(){
		Subject subject = SecurityUtils.getSubject();
		return subject.isAuthenticated()? "redirect:/":"sys/login";
	}
	
	
	@RequestMapping(value="/logout",method=RequestMethod.GET)
	public String logout(HttpServletRequest request, HttpServletResponse response, Model model){  
	     Subject subject = SecurityUtils.getSubject();
	    // 如果已经登录，则跳转到管理首页  
	    if(subject != null){  
	    	subject.logout();  
	    }  
	    return "redirect:/login";  
	}  
	
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(User currUser, Model model){
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			return "redirect:/";
		}
		
		UsernamePasswordToken token = new UsernamePasswordToken(
				currUser.getLoginName(), currUser.getPassword());
		if(currUser!=null&&StringUtils.isNotBlank(currUser.getMemberMe())&&currUser.getMemberMe().equals("yes")){
			token.setRememberMe(true);
		}
		try {
			subject.login(token);
		} catch (AuthenticationException e) {
			token.clear();
			model.addAttribute("message","账号密码错误");
			return "sys/login";
		}
		return "redirect:/";
	}
}
